<script setup lang="ts">
import { ShallowRef } from 'vue'
import { Object3D } from 'three'
import { MouseScrollInput } from '@/components/MouseScrollInput'

// 当前编辑对象
const editObject = inject<ShallowRef<Object3D>>('editObject')!

// Object3D对象禁止使用ref
const name = toRef(editObject.value.name)
const position = reactive({
  x: editObject.value.position.x,
  y: editObject.value.position.y,
  z: editObject.value.position.z,
})
const rotation = reactive({
  x: editObject.value.rotation.x,
  y: editObject.value.rotation.y,
  z: editObject.value.rotation.z,
})
const scale = reactive({
  x: editObject.value.scale.x,
  y: editObject.value.scale.y,
  z: editObject.value.scale.z,
})
const visible = toRef(editObject.value.visible)

watch(position, ({x, y, z}) => {
  editObject.value.position.set(x, y, z)
})
watch(rotation, ({x, y, z}) => {
  editObject.value.rotation.set(x, y, z, editObject.value.rotation.order)
})
watch(scale, ({x, y, z}) => {
  editObject.value.scale.set(x, y, z)
})

watch(visible, (visible) => {
  editObject.value.visible = visible
})

const pollData = () => {
  requestAnimationFrame(() => {
    if (!editObject.value) return
    position.x = editObject.value.position.x
    position.y = editObject.value.position.y
    position.z = editObject.value.position.z

    rotation.x = editObject.value.rotation.x
    rotation.y = editObject.value.rotation.y
    rotation.z = editObject.value.rotation.z

    scale.x = editObject.value.scale.x
    scale.y = editObject.value.scale.y
    scale.z = editObject.value.scale.z

    pollData()
  })
}

onMounted(() => {
  pollData()
})
</script>

<template>
  <el-form>
    <el-form-item label="名称">
      <el-input v-model="name" />
    </el-form-item>
    <el-form-item label="位置">
      <MouseScrollInput v-model="position.x" :step="0.1" />
      <MouseScrollInput v-model="position.y" :step="0.1" />
      <MouseScrollInput v-model="position.z" :step="0.1" />
    </el-form-item>
    <el-form-item label="旋转">
      <MouseScrollInput v-model="rotation.x" :step="1" type="angle" />
      <MouseScrollInput v-model="rotation.y" :step="1" type="angle" />
      <MouseScrollInput v-model="rotation.z" :step="1" type="angle" />
    </el-form-item>
    <el-form-item label="缩放">
      <MouseScrollInput v-model="scale.x" :step="0.01" />
      <MouseScrollInput v-model="scale.y" :step="0.01" />
      <MouseScrollInput v-model="scale.z" :step="0.01" />
    </el-form-item>
    <el-form-item label="可见性">
      <el-switch v-model="visible" />
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss"></style>
